﻿namespace Home
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Linq;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    using Home.ErrorHandling;

    public static class Program
    {
        public static void Main(string[] args)
        {
            var instanceHolder = default(IDisposable);

            try
            {
                if (args.Length == 0)
                {
                    throw new InvalidOperationException("The command line argument count is zero.");
                }

                var command = default(Command);
                var comment = default(string);

                var action = args[0];
                switch (action)
                {
                    case "wc":
                        command = new WebsiteCommentCommand();
                        comment = "Diamond: the website comment synchronization service is running, don't close the window.";
                        break;
                    case "wv":
                        command = new WebsiteVisitCommand();
                        comment = "Diamond: the website visit synchronization service is running, don't close the window.";
                        break;
                    default:
                        throw new InvalidOperationException(string.Format("The command line action {0} is invalid.", action));
                }

                if (EnsureOneInstance(command, out instanceHolder))
                {
                    Console.Out.WriteLine(comment);

                    var arguments = args.Skip(1).ToArray();
                    command.ExecuteAsync(arguments).GetAwaiter().GetResult();
                }
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.Error.WriteLine(ex.Message);
                Console.ResetColor();

                HandleErrorHelper.Handle(ex);
            }
            finally
            {
                if (instanceHolder != null) instanceHolder.Dispose();
            }
        }

        private static bool EnsureOneInstance(Command command, out IDisposable holder)
        {
            holder = null;
            var name = string.Format("Home.Client.Service-{0}", command.GetType().FullName);
            var createdNew = default(bool);
            holder = new Mutex(true, name, out createdNew);
            return createdNew;
        }
    }
}
